package com.inight.nightojbackendjudgeservice.rabbitmq;

import com.inight.nightojbackendjudgeservice.judge.JudgeService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class MyMessageConsumer {

    @Resource
    private JudgeService judgeService;


    /**
     * 消费者: 用于接收和处理消息
     * @param message
     * @param channel
     * @param deliveryTag
     */
    // 指定程序监听的消息队列和确认机制
    @SneakyThrows
    @RabbitListener(queues = {"code_queue"}, ackMode = "MANUAL") // manual 手动说明ack. 确认接收消息
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.info("receiveMessage message = {}", message);
        long questionSubmitId = Long.parseLong(message);
        // 在此处调用 判题服务
        try {
            judgeService.doJudge(questionSubmitId);
            // 手动确认收到消息. 返回 ack
            log.info("执行判题服务成功. questionSubmitId = {}", questionSubmitId);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            // throw new RuntimeException(e);
            log.error("执行判题服务失败. questionSubmitId = {}", questionSubmitId);
            // 第二个false 表示消息执行失败之后不重试. 不然一直重试会占内存
            channel.basicNack(deliveryTag, false, false);
        }
    }

}
